<template>
  <div :class="['mainTable', !autoHeight ? 'table-warp' : 'autoHeight']">
    <el-table
      size="small"
      ref="table"
      v-loading="loading"
      :data="data"
      tooltip-effect="dark"
      height="100%"
      :stripe="stripe"
      :default-sort="defaultSort"
      :row-key="rowKey"
      :highlight-current-row="highlightCurrentRow"
      :row-style="{ height: '42px' }"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @sort-change="sortChange"
      @select="select"
      @select-all="selectAll"
      @current-change="handleTableRowChange"
    >
      <template v-for="(item, IDX) in tempColumns">
        <el-table-column
          v-if="!item.type && isVif(item)"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <template v-if="item.children">
              <el-table-column
                v-for="(child, childIdx) in item.children"
                :key="IDX + childIdx"
                :label="child.label"
                :fixed="child.fixed"
                :min-width="child.minWidth"
                :width="child.width"
                :show-overflow-tooltip="
                  child.tooltip === 'false' ? false : true
                "
                :align="child.align"
              >
                <template slot-scope="scope">
                  {{ scope.row[item.prop] || "--" }}
                </template>
              </el-table-column>
            </template>
            <template v-else>
              {{ scope.row[item.prop] || "--" }}
            </template>
          </template>
        </el-table-column>
        <!-- 内置索引 -->
        <el-table-column
          v-if="item.type == 'index' && isVif(item)"
          label="序号"
          type="index"
          align="center"
          :fixed="item.fixed"
          width="50"
          :key="IDX"
        />

        <!-- 内置选择框 -->
        <el-table-column
          v-if="item.type == 'selection' && isVif(item)"
          type="selection"
          width="50"
          fixed
          align="center"
          :key="IDX"
          :selectable="item.selectable"
        />

        <!-- 普通表格项转换 -->
        <el-table-column
          v-if="item.type == 'formatter' && isVif(item)"
          :formatter="item.formatter"
          :label="item.label"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :prop="item.prop"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        ></el-table-column>

        <!-- 操作列 -->
        <el-table-column
          v-if="item.type == 'button' && isVif(item)"
          :label="item.label"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :prop="item.prop"
          :width="item.width"
          :show-overflow-tooltip="true"
          :align="item.align"
          :key="IDX"
        >
          <!-- 注意：:show-overflow-tooltip="true"  不能删掉，否则在动态columns 时，fixed 的宽度将会计算错误，此bug为el-table bug -->
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <ControlsRow :item="item" :scope="scope" :IDX="IDX" />
          </template>
        </el-table-column>

        <!-- 自定义表格项样式及转换 -->
        <el-table-column
          v-if="item.type == 'style' && isVif(item)"
          :label="item.label"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :prop="item.prop"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <div
              :style="item.style"
              :class="item.formatterClass(scope.row)"
              v-html="item.formatter(scope.row)"
              @click="item.click ? item.click(scope.row, scope.$index) : false"
            ></div>
          </template>
        </el-table-column>

        <!-- 插槽类型 -->
        <el-table-column
          v-if="item.type == 'slot' && isVif(item)"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <slot
              :name="item.slotName"
              :row="scope.row"
              :index="scope.$index"
            ></slot>
          </template>
        </el-table-column>

        <!-- 基金公司跳转 -->
        <el-table-column
          v-if="item.type == 'companyHref' && isVif(item)"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <a style="color: #2377cc" @click="toShowCompany(row, item.openKey)">
              {{ row[item.prop] ? row[item.prop] : "--" }}
            </a>
          </template>
        </el-table-column>

        <!-- 基金经理和基金产品跳转 -->
        <el-table-column
          v-if="item.type == 'managerHref' && isVif(item)"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <TableRowHrefText
              :row="row"
              :column="item"
              :managerNameField="item.managerNameField"
              :managerCodeField="item.managerCodeField"
              :fundDetailType="item.fundType || 'PUBLIC'"
            />
          </template>
        </el-table-column>

        <el-table-column
          v-if="item.type == 'riskTypeIcon' && isVif(item)"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <RiskTypeIcon :row="row" :column="item" />
          </template>
        </el-table-column>
        <!-- 文字显示样式 -->
        <el-table-column
          v-if="item.type == 'withColorRatio' && isVif(item) && !item.formatter"
          :label="item.label"
          :prop="item.prop"
          :fixed="item.fixed"
          :min-width="minWidthHandler(item)"
          :width="item.width"
          :show-overflow-tooltip="isShowTooltip(item)"
          :align="item.align"
          :key="IDX"
          :sortable="item.sortable"
          :sort-method="item.sortMethod"
        >
          <template slot="header">
            {{ item.label }}
            <el-tooltip v-if="item.description" effect="dark" placement="top">
              <i class="iconfont icon-fof-shuoming headerTip"></i>
              <template slot="content">
                {{ item.description }}
              </template>
            </el-tooltip>
          </template>
          <template slot-scope="{ row }">
            <TableRowTextColorRatio
              :row="row"
              :column="item"
              :colorPropField="colorPropField"
            />
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 页码 -->
    <div class="pagination_warp" v-if="isShowPage">
      <span>共{{ Number(pagination.total) }}条</span>
      <el-pagination
        :current-page="Number(pagination.current)"
        :page-sizes="pagination.pageSizes || [10, 20, 30, 50]"
        :page-size="Number(pagination.size)"
        :layout="pagination.layout || 'sizes, prev, pager, next, jumper'"
        :total="Number(pagination.total)"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script>
import TableRowHrefText from "./components/tableRowHrefText"
import TableRowTextColorRatio from "./components/tableRowTextColorRatio"
import ControlsRow from "./components/controlsRow"
import RiskTypeIcon from "./components/riskTypeIcon/index.vue"
export default {
  name: "HHHH",
  components: {
    TableRowHrefText,
    TableRowTextColorRatio,
    ControlsRow,
    RiskTypeIcon,
  },
  props: {
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    colorPropField: {
      type: String,
      default: "percentFormat",
    },
    // 是否自动高度
    autoHeight: {
      type: Boolean,
      default: false,
    },
    // 是否加载
    loading: {
      type: Boolean,
      default: false,
    },
    // 是否 设置默认排序，需要column设置sortable
    defaultSort: {
      type: Object,
      default: () => ({ prop: "", order: "" }),
    },
    // 是否为斑马纹
    stripe: {
      type: Boolean,
      default: false,
    },
    // 表头
    columns: {
      type: Array,
      default: () => [],
    },
    // 表格数据
    data: {
      type: Array,
      default: () => [],
    },
    // 页码
    pagination: {
      type: Object,
      default: () => ({
        current: 1,
        total: 0,
        size: 10,
        pageSizes: [10, 20, 30, 50],
        layout: "sizes, prev, pager, next, jumper",
      }),
    },
    // 是否需要显示分页
    isShowPage: {
      type: Boolean,
      default: true,
    },
    // 行标识
    rowKey: {
      type: String,
      default: "id",
    },
    // 多选数组
    multipleSelection: {
      type: Array,
      default: () => [],
    },
    // 表格项默认的最小宽度
    rowMinWidth: {
      type: [Number, String],
      default: "100",
    },
  },
  data() {
    return {
      tableData: [],
      radio: "",
      tempColumns: [],
      currentTableRow: null,
    }
  },
  watch: {
    data: {
      immediate: true,
      handler(newV) {
        if (!Array.isArray(newV) | !newV.length) return
        this.getNowTableData(newV)
      },
    },
    columns: {
      immediate: true,
      deep: true,
      handler(newV) {
        if (!Array.isArray(newV)) console.warn("columns-需要数组！")
        let tempColumns = newV.map(item => {
          if (item.type == "withColorRatio") {
            let percentFormat = item[this.colorPropField]
            switch (percentFormat.toString()) {
              case "1":
                item = {
                  ...item,
                  align: "right",
                  tdSlot: {
                    slotName: "withColorRatio",
                    ratio: 100,
                    suffix: "%", // 文本后缀
                  },
                }
                break
              case "2":
                item = {
                  ...item,
                  align: "right",
                  tdSlot: {
                    toFixedInt: 4,
                  },
                }
                break
              case "3":
                item = {
                  ...item,
                  align: "right",
                  tdSlot: {
                    toFixedInt: 2,
                  },
                }
                break
              case "4":
                item = {
                  ...item,
                  align: "right",
                  tdSlot: {
                    toFixedInt: 2,
                    ratio: 100,
                    suffix: "%",
                  },
                }
                break
              case "5":
                item = {
                  ...item,
                  align: "right",
                  tdSlot: {
                    ratio: 1,
                    slotName: "withColorRatio",
                  },
                }
                break
            }
          }
          return item
        })
        this.tempColumns = tempColumns
      },
    },
  },
  computed: {
    minWidthHandler() {
      return item => {
        if (item.minWidth) {
          return item.minWidth
        } else if (item.description || item.type == "button") {
          return "120"
        } else {
          if (!item.label) return "120"
          return 16 * (item.label.length + 3)
        }
      }
    },
    isShowTooltip() {
      return item => {
        let flag = item.hasOwnProperty("tooltip")
        if (flag) {
          return item.tooltip
        } else {
          return true
        }
      }
    },
    isVif() {
      return item => {
        let flag = item.hasOwnProperty("vIf")
        if (flag) {
          return item.vIf
        } else {
          return true
        }
      }
    },
  },
  methods: {
    // 高亮行切换回调
    handleTableRowChange(row) {
      this.currentTableRow = row
      this.$emit("handleRowChange", row)
    },
    // 表格数据变化后的操作
    getNowTableData(newTableData) {
      console.warn(
        "如果当前table有选择框，请注意传入组件rowKey，否则跨页勾选会出错！当前：",
        this.rowKey
      )
      const arr = newTableData.filter(item =>
        this.multipleSelection.some(it => it[this.rowKey] === item[this.rowKey])
      )
      this.$nextTick(() => {
        // 要用nextTick(()={})去更新页面
        arr.forEach(row => {
          // 将数据进行回显
          this.$refs.table.toggleRowSelection(row, true)
        })
      })
    },
    // 勾选单个数据
    select(selection, row) {
      //selection 为当前页已勾选的数组；row为当前操作的某一行数据
      // 判断是否勾选
      let checkedTrue = selection.length && selection.indexOf(row) !== -1
      if (!checkedTrue) {
        // 取消勾选,使用filter()方法过滤掉刚刚勾选的那一条数据
        let newMultipleSelection = this.multipleSelection.filter(
          item => item[this.rowKey] != row[this.rowKey]
        )
        this.$emit("update:multipleSelection", newMultipleSelection)
      }
      if (checkedTrue) {
        // 勾选，将刚刚勾选的数据用push()方法放进数组
        this.multipleSelection.push(row)
      }
    },
    // 全选
    selectAll(selection) {
      // selection 为当前页面的勾选数组
      if (selection.length > 0) {
        // 全选，将本页面所有（可以勾选的）数据放入自定义的勾选数组里
        // this.multipleSelection.push(...selection)
        // 需要过滤掉原列表中已选中的
        let oldRowKeys = this.multipleSelection.map(item => {
          return item[this.rowKey]
        })
        selection.forEach(item => {
          if (!oldRowKeys.includes(item[this.rowKey])) {
            this.multipleSelection.push(item)
          }
        })
      } else {
        // 取消全选，将本页面所有（可以勾选的）数据用filter()＋every()方法过滤掉
        let newList = this.multipleSelection.filter(
          item => this.data.every(it => it[this.rowKey] != item[this.rowKey])
          // every方法，数组里面所有数据为真则返回真
        )

        this.$emit("update:multipleSelection", newList)
      }
    },
    // 表单
    handleSelectionChange() {
      // this.$emit("update:multipleSelection", this.multipleSelection)
      // this.$emit("select", this.multipleSelection)
    },

    handleRowClick(row, column, event) {
      this.$emit("rowClick", row, column, event)
    },

    handleRadioChange(val) {
      this.$emit("select", val)
    },

    // 页码
    handleSizeChange(val) {
      this.$emit("update:pagination", {
        current: this.pagination.current,
        total: this.pagination.total,
        size: val,
      })
      this.$emit("pageChange", this.pagination)
    },
    handleCurrentChange(val) {
      this.$emit("update:pagination", {
        current: val,
        total: this.pagination.total,
        size: this.pagination.size,
      })
      this.$emit("pageChange", this.pagination)
    },

    handleClearSelection() {
      this.radio = ""
    },
    sortChange(val) {
      this.$emit("sortChange", val)
    },
    /* 跳转查看基金公司 */
    async toShowCompany(row, key) {
      let { href } = this.$router.resolve({
        path: "manage/CompanyDetailsIndex",
        query: {
          companyCode: row[key],
        },
      })
      this.$utils.openBlank(href, this)
    },
  },
}
</script>

<style lang="less" scoped>
.headerTip {
  color: #8a94a6;
  position: relative;
  top: 2px;
}
.table-warp {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  /deep/ .el-table {
    flex: 1;
    height: calc(100% - 48px) !important;
  }
}
.autoHeight {
  height: 100%;

  /deep/ .el-table__body-wrapper {
    height: 100% !important;
  }
}

.mainTable {
  /deep/ .el-table__fixed-body-wrapper {
    top: 48px !important;
  }

  /deep/ .el-table__fixed {
    height: calc(100% - 8px) !important;
  }
  .pagination_warp {
    height: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
    /deep/ .btn-prev,
    /deep/ .btn-next {
      background: #fff;
      border: 1px solid #c0c4cc;
    }
    /deep/ .el-pager {
      .el-icon {
        background: #fff;
      }
      .number {
        background: #fff;
        border: 1px solid #c0c4cc;
      }
      .active {
        color: #4e5d78 !important;
        background: #fff !important;
        border: 1px solid #232d3e;
      }
    }
  }

  /deep/ .el-table__row .el-table__cell {
    min-height: 42px !important;
    height: auto !important;
    padding: 0;
    .cell {
      // 不让排序按钮导致换行   与表头对齐
      padding: 0 12px !important;
    }
  }
  /deep/ .el-table__header .el-table__cell {
    color: #333;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 20px;
    background-color: #fafafa;
    height: 48px;
    padding: 0;
    .cell {
      // 不让排序按钮导致换行
      padding: 0 12px !important;
      text-overflow: unset !important;
      white-space: nowrap !important;
    }
  }

  .table_row_btn_list {
    display: flex;
    align-items: left;
    .el-button {
      height: 36px;
      display: flex;
      align-items: left;
    }
  }
  /deep/ .el-table::before,
  /deep/ .el-table__fixed::before {
    display: none !important;
  }
}
</style>
